﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YAPL.Language.Ast.Utils;

namespace YAPL.Language.Ast {
	public class ConditionalExpression : Expression {
		private Expression _condition;
		private CodeBlockExpression _thenBlock;
		private CodeBlockExpression _elseBlock;
		public ConditionalExpression(ExpressionType nodeType, Type type, Expression condition, CodeBlockExpression thenBlock, CodeBlockExpression elseBlock) : base(nodeType, type) {
			_condition = condition;
			_thenBlock = thenBlock;
			_elseBlock = elseBlock;
		}

		public ConditionalExpression(ExpressionType nodeType, Type type, bool canRead, bool canWrite, Expression condition, CodeBlockExpression thenBlock, CodeBlockExpression elseBlock) : base(nodeType, type, canRead, canWrite) {
			_condition = condition;
			_thenBlock = thenBlock;
			_elseBlock = elseBlock;
		}

		[Descendant(AstVisit.AfterCurrent, Priority = 0)]
		public Expression Condition {
			get { return _condition; }
		}

		[Descendant(AstVisit.AfterCurrent, Priority = 1)]
		public CodeBlockExpression ThenBlock {
			get { return _thenBlock; }
		}

		[Descendant(AstVisit.AfterCurrent, Priority = 2)]
		public CodeBlockExpression ElseBlock {
			get { return _elseBlock; }
		}

		public override bool NodeEquals(Expression other) {
			return (other is ConditionalExpression);
		}

		public override bool RewriteChild(Expression child, Expression newExpression) {
			var rewritten = false;
			if (ReferenceEquals(_condition, child)) {
				_condition = newExpression;
				rewritten = true;
			}
			if (ReferenceEquals(_thenBlock, child)) {
				_thenBlock = newExpression as CodeBlockExpression;
				rewritten = true;
			}

			if (ReferenceEquals(_elseBlock, child)) {
				_elseBlock = newExpression as CodeBlockExpression;
				rewritten = true;
			}
			return rewritten;
		}
	}
}
